<template>
   <div class="app-container">
      <div class="head-container">
         <a-form ref="queryRef" :model="queryParams" layout="inline">
            <a-form-item field="deptName">
               <a-input v-model="queryParams.deptName" :style="{ width: '150px' }" placeholder="部门名称" clearable
                  prefix-icon="Search" allow-clear />
            </a-form-item>
            <a-form-item field="status">
               <a-select v-model="queryParams.status" :style="{ width: '150px' }" placeholder="用户状态" allow-clear>
                  <a-option v-for="item in sys_normal_disable" :value="item.value" :label="item.label"></a-option>
               </a-select>
            </a-form-item>
            <a-form-item>
               <a-space>
                  <a-button type="primary" @click="handleQuery">
                     <template #icon>
                        <icon-search />
                     </template>
                     搜索
                  </a-button>
                  <a-button @click="resetQuery">
                     <template #icon>
                        <icon-refresh />
                     </template>
                     重置
                  </a-button>
               </a-space>
            </a-form-item>
         </a-form>
      </div>
      <div class="main-container">
         <div class="main-toolbar">
            <a-button size="small" type="primary" @click="showAddUser">新增</a-button>
            <a-button size="small" status="danger" type="primary" @click="handleDelete"
               :disabled="selectedKeys.length === 0">删除</a-button>
            <a-button size="small" status="warning" type="primary" @click="handleResetPwd"
               :disabled="selectedKeys.length === 0">重置密码</a-button>
         </div>
         <div class="main-content">
            <a-table :columns="columns" row-key="userId" :row-selection="{ type: 'checkbox', showCheckedAll: true }"
               @selection-change="handleSelectionChange" :data="userList" :loading="loading">
               <template #userName="{ record }">
                  <a-button type="text" @click="showEditUser(record.userId)">{{ record.userName }}</a-button>
               </template>
               <template #status="{ record }">
                  <a-switch v-model="record.status" @change="handleStatusChange(record)" type="round" checked-value="0"
                     unchecked-value="1">
                     <template #checked>
                        启用
                     </template>
                     <template #unchecked>
                        停用
                     </template>
                  </a-switch>
               </template>
            </a-table>
         </div>
      </div>
      <UserForm ref="userForm"></UserForm>
   </div>
</template>

<script setup name="User">
import { changeUserStatus, delUser, deptTreeSelect, listUser, resetUserPwd } from "@/api/system/user";
import { getCurrentInstance, reactive, ref, toRefs, watch } from "vue";
import { useRouter } from "vue-router";
import UserForm from "./userForm";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict("sys_normal_disable", "sys_user_sex");

const userList = ref([]);
const loading = ref(true);
const total = ref(0);
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);

const userForm = ref();
const showAddUser = () => {
   userForm.value.init('add')
}

const showEditUser = (id) => {
   userForm.value.init('edit', id)
}

// 列显隐信息
let selectedKeys = ref([]);
const columns = ref([
   { key: 0, title: `用户编号`, dataIndex: 'userId' },
   { key: 1, title: `用户名称`, dataIndex: 'userName', slotName: 'userName' },
   { key: 2, title: `用户昵称`, dataIndex: 'nickName' },
   { key: 3, title: `部门`, dataIndex: 'deptName' },
   { key: 4, title: `手机号码`, dataIndex: 'phonenumber' },
   { key: 5, title: `状态`, dataIndex: 'status', slotName: 'status' },
   { key: 6, title: `上次登录时间`, dataIndex: 'loginDate' }
]);

const data = reactive({
   form: {},
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      userName: undefined,
      phonenumber: undefined,
      status: undefined,
      deptId: undefined
   },
});

const { queryParams } = toRefs(data);

/** 根据名称筛选部门树 */
watch(deptName, val => {
   proxy.$refs["deptTreeRef"].filter(val);
});

/** 查询部门下拉树结构 */
function getDeptTree() {
   deptTreeSelect().then(response => {
      deptOptions.value = response.data;
   });
};

/** 查询用户列表 */
function getList() {
   loading.value = true;
   listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(({ data }) => {
      loading.value = false;
      userList.value = data.rows;
      total.value = data.total;
   });
};

/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
};

/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
};

/** 删除按钮操作 */
function handleDelete(row) {
   const userIds = row.userId || selectedKeys.value;
   proxy.$modal.confirm({
      title: '系统提示',
      content: '是否确认删除选中用户的数据项？',
      onOk: () => {
         delUser(userIds).then(() => {
            getList();
            selectedKeys.value = []
            proxy.$message.success("删除成功")
         })
      }
   })
};

/** 用户状态修改  */
function handleStatusChange(row) {
   let text = row.status === "0" ? "启用" : "停用";
   proxy.$modal.confirm({
      title: '系统提示',
      content: `确认要${text}${row.userName}用户吗?`,
      onOk: () => {
         changeUserStatus(row.userId, row.status).then(() => {
            proxy.$message.success(text + "成功");
         }).catch(err => {
            row.status = row.status === "0" ? "1" : "0";
         })
      },
      onCancel: () => {
         row.status = row.status === "0" ? "1" : "0";
      }
   });
};
/** 更多操作 */
function handleCommand(command, row) {
   switch (command) {
      case "handleResetPwd":
         handleResetPwd(row);
         break;
      case "handleAuthRole":
         handleAuthRole(row);
         break;
      default:
         break;
   }
};
/** 跳转角色分配 */
function handleAuthRole(row) {
   const userId = row.userId;
   router.push("/system/user-auth/role/" + userId);
};

/** 重置密码按钮操作 */
function handleResetPwd() {
   let pwd = "123456"
   proxy.$modal.confirm({
      title: "重置密码",
      content: "您确定要重置选中用户密码吗？",
      onOk: () => {
         resetUserPwd(selectedKeys.value, pwd).then(() => {
            proxy.$message.success("修改成功，新密码是：" + pwd);
         });
      }
   })
};

/** 选择条数  */
function handleSelectionChange(selection) {
   selectedKeys.value = selection
};

getDeptTree();
getList();
</script>
